#include "referee.h"
#include "monitor.h"

uint8_t referee_buffer[250] = {};
ext_game_robot_status_t referee_game_robot_status;
ext_power_heat_data_t referee_power_heat_data;
ext_game_status_t referee_game_status;

void referee_init()
{
	__HAL_UART_ENABLE_IT(&huart6, UART_IT_RXNE);
	__HAL_UART_ENABLE_IT(&huart6, UART_IT_IDLE);
	HAL_UART_Receive_DMA(&huart6, referee_buffer, sizeof(referee_buffer));
}

void referee_callback()
{
	if (__HAL_UART_GET_FLAG(&huart6, UART_FLAG_IDLE) != RESET)
	{
		__HAL_UART_CLEAR_IDLEFLAG(&huart6);
		HAL_UART_DMAStop(&huart6);
		extern DMA_HandleTypeDef hdma_usart6_rx;
		uint16_t cmd_id = 0;//(referee_buffer[6] << 8) | referee_buffer[5];
		uint16_t data_length = sizeof(referee_buffer) - __HAL_DMA_GET_COUNTER(&hdma_usart6_rx);
		for(int i = 0; i < data_length; i++)
		{
			if(referee_buffer[i] == 0xA5)
			{
				cmd_id = (referee_buffer[i + 6] << 8) | referee_buffer[i + 5];
				switch (cmd_id)
				{
					case 0x0201:
						if((i + 7 + sizeof(referee_game_robot_status)) > sizeof(referee_buffer))break;
						memcpy(&referee_game_robot_status, referee_buffer + i + 7, sizeof(referee_game_robot_status));
						break;
					case 0x0202:
						if(i + 7 + sizeof(referee_power_heat_data) > sizeof(referee_buffer))break;
						memcpy(&referee_power_heat_data, referee_buffer + i + 7, sizeof(referee_power_heat_data));
						break;
				}
			}
		}
		HAL_UART_Receive_DMA(&huart6, referee_buffer, sizeof(referee_buffer));
	}
	monitor_refresh(&monitor_referee_online);
}